import { gqcPermissionCheck } from '@kuiper/auth';
import set from 'lodash/set';

export default server => {
	const {
		app: {
			model: { ResultNumbers },
		},
	} = server;

	server.methods.registerGraphQLSchema({
		name: 'ResultNumbers',
		model: ResultNumbers,
		queryFields: {
			Many: 'findMany',
		},
		onPreAddFields(tc) {
			const {
				app: {
					graphqlResolvers,
					schemaComposer,
					schema: { Job },
				},
			} = server;
			const IResultNumberDateRange = schemaComposer.createInputTC({
				name: 'IResultNumberDateRange',
				fields: {
					startTime: 'Date',
					endTime: 'Date',
				},
			});

			const permissionCheck = gqcPermissionCheck({
				required: 'cloud-monitor\x01listTask',
				selfOnlyArgsBuilder(
					_source,
					args,
					{
						request: {
							auth: {
								credentials: { uid },
							},
						},
					}
				) {
					set(args, ['filter', 'uid'], uid);
				},
			});

			tc.addRelation('job', {
				resolver: () => Job.mongooseResolvers.dataLoader({ lean: true }),
				prepareArgs: {
					_id: source => source.jobId,
				},
				projection: { jobId: 1 },
			});

			graphqlResolvers.Query.ResultNumbersMany = graphqlResolvers.Query.ResultNumbersMany.withMiddlewares(
				[permissionCheck]
			).addFilterArg({
				name: 'dateRange',
				type: IResultNumberDateRange,
				description: 'dateRange.startTime >= x && dateRange.endTime <= x',
				query: (query, value) => {
					if (value.startTime) query.datetime = { $gte: value.startTime };
					if (value.endTime)
						query.datetime = {
							...query.datetime,
							$lte: value.endTime,
						};
				},
			});
		},
	});
};
